package com.dalei.vds;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;

import com.dalei.vds.environment.CurrentTask;
import com.dalei.vds.model.ImageType;
import com.dalei.vds.widget.ImageGridViewBinder;
import com.dalei.vds.xml.ImageTypeXMLReader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class OutlineImagesActivity extends Activity {
	
	private static final int REQUEST_IMAGE_VIEWER = 0x00000040;

	private static final String FIELD_ID = "id";

	private static final String FIELD_VALUE = "value";

	private static final String FIELD_TEXT = "text";

	private static final String FIELD_CODE = "code";

	private static final String FIELD_IMAGE = "image";

	private GridView gridView;

	private SimpleAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.outlineimages);
		
		gridView = (GridView) findViewById(R.id.images_grid);
		adapter = new SimpleAdapter(this, getData(), R.layout.item_image,
				new String[] { FIELD_TEXT, FIELD_IMAGE }, new int[] {
						R.id.item_image_title, R.id.item_image_picture });
		adapter.setViewBinder(new ImageGridViewBinder());
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				int imageValue = -1;
				ListAdapter listAdapter = (ListAdapter) parent.getAdapter();
				Map<String, Object> map = (Map<String, Object>) listAdapter
						.getItem(position);
				Object value = map.get(FIELD_VALUE);
				if (value instanceof Integer) {
					imageValue = (Integer) value;
				}
				
				String imageTitle = null;
				value = map.get(FIELD_TEXT);
				if (value instanceof String) {
					imageTitle = (String) value;
				}

				Intent intent = new Intent();
				intent.setClass(OutlineImagesActivity.this, ImageViewerActivity.class);
				intent.putExtra(ImageViewerActivity.PARAMETER_GRID_ID, position);
				intent.putExtra(ImageViewerActivity.PARAMETER_IMAGE_VALUE, imageValue);
				intent.putExtra(ImageViewerActivity.PARAMETER_IMAGE_TITLE, imageTitle);
				
				startActivityForResult(intent, REQUEST_IMAGE_VIEWER);
			}
		});

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_IMAGE_VIEWER:
			int gridId = -1;
			int imageValue = -1;

			switch (resultCode) {
			case ImageViewerActivity.RESULT_MODIFIED:
				gridId = data.getIntExtra(
						ImageViewerActivity.PARAMETER_GRID_ID, -1);
				imageValue = data.getIntExtra(
						ImageViewerActivity.PARAMETER_IMAGE_VALUE, -1);
				if ((gridId >= 0) && checkImageValue(imageValue)) {
					File imageSource = CurrentTask.getImages().get(imageValue);
					if (imageSource != null) {
						if (imageSource.exists()) {
							Map<String, Object> map = (Map<String, Object>) adapter
									.getItem(gridId);
							map.put(FIELD_IMAGE, imageSource);
							adapter.notifyDataSetChanged();
						} else {
							Toast.makeText(this,
									getString(R.string.image_file_not_exist),
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(this,
								getString(R.string.get_image_file_failed),
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(this, getString(R.string.invalid_parameter),
							Toast.LENGTH_SHORT).show();
				}
				break;

			case ImageViewerActivity.RESULT_REMOVE:
				gridId = data.getIntExtra(
						ImageViewerActivity.PARAMETER_GRID_ID, -1);
				imageValue = data.getIntExtra(
						ImageViewerActivity.PARAMETER_IMAGE_VALUE, -1);
				if ((gridId >= 0) && checkImageValue(imageValue)) {
					Map<String, Object> map = (Map<String, Object>) adapter
							.getItem(gridId);
					map.put(FIELD_IMAGE, R.drawable.defaultpic);
					adapter.notifyDataSetChanged();
				} else {
					Toast.makeText(this, getString(R.string.invalid_parameter),
							Toast.LENGTH_SHORT).show();
				}
				break;

			default:
				break;
			}
			break;

		default:
			break;
		}
	}

	private List<Map<String, Object>> getData() {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		InputStream in = null;
		try {
			in = getAssets().open("image_type.xml");
			ImageTypeXMLReader reader = new ImageTypeXMLReader(in);
			reader.read();

			List<ImageType> imageTypes = reader.imageTypes();
			if (imageTypes != null) {
				for (ImageType imageType : imageTypes) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put(FIELD_ID, imageType.getId());
					map.put(FIELD_VALUE, imageType.getValue());
					map.put(FIELD_CODE, imageType.getCode());
					map.put(FIELD_TEXT, imageType.getText());
					File src = CurrentTask.getImages()
							.get(imageType.getValue());
					if (src != null) {
						map.put(FIELD_IMAGE, src);
					} else {
						map.put(FIELD_IMAGE, R.drawable.defaultpic);
					}

					data.add(map);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return data;
	}

	private boolean checkImageValue(int value) {
		final int[] in = new int[] { 5, 6, 7, 8, 9, 10, 11, 12 };
		for (int i = 0; i < in.length; i++) {
			if (value == in[i]) {
				return true;
			}
		}
		return false;
	}
}
